﻿using System;
using System.Threading.Tasks;

namespace ShareHelper
{
    /// <summary>
    /// 异步任务帮助类
    /// </summary>
    public static class TaskHelper
    {
        /// <summary>
        ///  带异常输出的Task
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public static Task Run(Action action)
        {
            if (action == null)
                return null;
            return Task.Run(action).ContinueWith(t => { Exception(t.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
        }

        /// <summary>
        /// 有返回值 带异常输出的Task
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="function"></param>
        /// <returns></returns>
        public static Task<TResult> Run<TResult>(Func<TResult> function)
        {
            if (function == null) return null;
            return Task.Run(function).ContinueWith<TResult>(t =>
            {
                Exception(t.Exception);
                return default;
            }, TaskContinuationOptions.OnlyOnFaulted);
        }

        ///<summary>
        /// 异步委托任务异常捕获
        ///</summary>
        /// <param name="e"></param>
        private static void Exception(AggregateException e)
        {
            foreach (var item in e.InnerExceptions)
            {
                Log.Error("异步委托任务异常捕获", item);
            }
        }
    }
}